﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace myWinForm
{
    class MySocket
    {
        private ReceiveMessageDelegate _receiveMessageDelegate;
        private string _serverIp;
        private int _serverPort;
        private Socket _socket;
        private Thread _thread;

        private void Start()
        {
            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var localEndPoint = new IPEndPoint(IPAddress.Parse(_serverIp), _serverPort);
                _socket.Bind(localEndPoint);
                _socket.Listen(10);
                _thread = new Thread(ReceiveAccept);
                _thread.Start();
             
            }
            catch (SocketException se)
            {
                throw new Exception(se.Message);
            }
        }

        private void Stop()
        {
            try
            {
                _thread.Abort(); // 线程终止
                _socket.Close(); // Socket Close
           
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        private void ReceiveAccept()
        {
            while (true)
            {
                var client = new Client();
                try
                {
                    client.ClientSocket = _socket.Accept();
            
                    _receiveMessageDelegate = ReceiveMessages;
                    _receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        private void ReceiveMessages(Client client)
        {
            while (true)
            {
                var receiveBuffer = new byte[1024];
                client.ClientSocket.Receive(receiveBuffer);
                var strReceiveData = Encoding.Unicode.GetString(receiveBuffer);
                if (!string.IsNullOrEmpty(strReceiveData))
                {
                 
                    var strSendData = "OK. The content is:" + strReceiveData;
                    var sendBuffer = Encoding.Unicode.GetBytes(strSendData);
                    client.ClientSocket.Send(sendBuffer);
                }
            }
        }

        private void ReceiveMessagesCallback(IAsyncResult ar)
        {
            _receiveMessageDelegate.EndInvoke(ar);
        }


        private delegate void ReceiveMessageDelegate(Client client);

        /// <summary>
        ///     客户端会话信息类
        /// </summary>
        public class Client
        {
            public Socket ClientSocket { get; set; }
        }

        private void cmbIp_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
